/*
Mandala 是一个小型轻量级的ajax框架，
封装了网页设计常用的一些功能。
扩展了string,array,object,function
最后更新日期:2008-3-14
版本1.3
1、实现了选择器
2、实现了ajax
3、对[string、array、function、object]进行了功能上的扩展;
*/
//以下代码可以提速ie
/*@cc_on
eval((function(props) {
  var code = [];
  for (var i = 0, l = props.length;i<l;i++){
    var prop = props[i];
    window['_'+prop]=window[prop];
    code.push(prop+'=_'+prop)
  }
  return 'var '+code.join(',');
})('document self top parent alert setInterval clearInterval setTimeout clearTimeout'.split(' ')));
@*/

if(typeof(Mandala)!="function"){
(function(){
	// 定义Mandala
	var M=window.Mandala=function(){};		 
	//浏览器对像;
	var userAgent = navigator.userAgent.toLowerCase();	
	

	M.UID = 0;	 
	//对像扩展
	M.Extend=function(a,b){
		for(i in (b||{})){
			a[i]=b[i];
		};
		return a;
	};
	M.Extend(M,{
			Ver:'1.3',
			ModDate:'2009-4-26',
			$Random:function(Min,Max){return Math.floor(Math.random() * (Max - Min + 1) + Min);},
			$Time:function(){return new Date().getTime();},
			$Defined:function(o){return o!= "undefined"},
			$Browser: {
				version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [])[1],
				safari: /webkit/.test( userAgent ),
				opera: /opera/.test( userAgent ),
				msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
				mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ),
				isStrict: document.compatMode == "CSS1Compat"				 
			 },
            $Jpath:(function(){
				var scripts = document.getElementsByTagName("script");	 
				return scripts.length ? scripts[scripts.length - 1].getAttribute("src").replace(/[^\/]+$/g,'') : null;
			})(),
			//按对像生成数组 ;
			$A:function(o){
				if (!o)return [];
				if (o.toArray) {
					return o.toArray();
				} else {
						var a = [];
						for (var i = 0, l = o.length; i < l; i++) {
						  a.push(o[i]);
						}
						return a;
				}				
			},
			UID: function() {
				return M.UID++;
			},
			//挑选；
			$P:function(){
				for (var i = 0, l = arguments.length; i < l; i++){
					if (M.$Defined(arguments[i])) return arguments[i];
				}
				return null;			
			},
			$splat:function(o){
				var type = $type(o);
				return (type) ? ((type != 'array' && type != 'arguments') ? [o] : o) : [];
			},
		    //叛断有没有定义;
			$defined:function(s){
				return s!=""&&s!=null&&s!=undefined;
			},
			$try:function(fn, bind, args){
				try {
					return fn.apply(bind, M.$splat(args));
				} catch(e){
					return false;
				}
			},
			 //把xml转化为Dom
			$toXml:function(strXml){
				var XmlDoc=null;
				if(M.$Browser.msie){
					XmlDoc = new ActiveXObject("Microsoft.XMLDOM"); 
					XmlDoc.loadXML(strXml);
				}
				if(M.$Browser.mozilla){
					XmlDoc = (new DOMParser()).parseFromString(strXml, "text/xml");
				}
				return XmlDoc;			
			 },
			$attr: function(obj, attrList, value) {
				if (this.isString(attrList)) {
					attrList = attrList.split('.');
				}
			   var t1;
				for (var i = 0, idx = attrList.length - 1; i < idx; i++) {
					t1 = obj;
					obj = obj[attrList[i]];
					if(typeof obj == 'undefined' || obj === null)
						t1[attrList[i]] = obj = {};
				}
				if (value == undefined) {
					return obj[attrList[i]];
				}
				obj[attrList[i]] = value;
         }


	});
//对像模型
//$M.Mobj为对像的管理模型
//设置一个属性或方法用set+属性(方法)名;
//获取一个属性用get+属性名;
//获取一个方法用get+方法名+()

	M.Mobj=function ( properties ) {
		var objRef = this;
		for ( var i in properties ) {
			(function(){
				var key = i;
				objRef[ "get" + key ] = function() {
					return properties[key];
				};
				objRef[ "set" + key ] = function(val) {
					properties[key] = val;
				};
		   })(); 
		};
	}	
	//扩展String;
	M.Extend(String.prototype,{
			bytes:function(){return this.replace(/[^\x00-\xff]/g,"--").length;},
			trim: function(){return this.replace(/^\s+|\s+$/g, '');},			
			test: function(regex, params){return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this);},
			clean: function(){return this.replace(/\s{2,}/g, ' ').trim();},
			camelize : function(){return this.replace(/(-\S)/g,function($1){return $1.toUpperCase().substring(1,2)});},
			escapeRegExp: function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');},
			toInt: function(base){return parseInt(this, base || 10);},
			toFloat: function(){return parseFloat(this);},
			toNum:function(){return Number(this.replace(/[^\d\.]/g,''));},
			stripScripts: function(evaluate){
				var scripts = '';
				var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
					scripts += arguments[1] + '\n';
					return '';
				});
				if (evaluate && scripts) $exec(scripts);
				return text;
			},
			left:function(n){return this.slice(0,n);},
			right:function(n){return this.slice(this.length-n);},
			request:function(key){
				if(typeof(this)=="undefined")return false;
				if(this.length>0) { 
					var s = this.split("&"); 
					for(var i=0;i<s.length;i++){
						var sp=s[i].split("=")
						if(sp[0]==key) return(sp[1]);
					}
					return false;
				} 
				else
				return false
			},
			//得到颜色的aplha
			alphaColor:function(alpha){
				var s=this.replace("#","");
				var rgb1=s.match(/../g);
				var rgb=new Array();
				for(var i=0;i<rgb1.length;i++)
				{
					rgb.push(eval("0x"+rgb1[i]));
				}
				var rgb2=[];
				for(var i=0;i<rgb.length;i++)
				{
					rgb2.push(parseInt(rgb[i]*alpha+255*(1-alpha)).toString(16));
				}
				return ""+rgb2.join("");
			},
			// HTML编码
			HTMLEncode:function(){
				var re = this;
				var q1 = [/\x26/g,/\x3C/g,/\x3E/g,/\x20/g];
				var q2 = ["&amp;","&lt;","&gt;","&nbsp;"];
				for(var i=0;i<q1.length;i++)
				re = re.replace(q1[i],q2[i]);
				return re;
			},
			// Unicode转化
			 ascW:function(){
				var strText = "";
				for (var i=0; i<this.length; i++) strText += "&#" + this.charCodeAt(i) + ";";
				return strText;
			}		
	})
	//扩展Array;
	M.Extend(Array.prototype,{	
				each: function(fn, bind){
					for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this);
				},
				every: function(fn, bind){
					for (var i = 0, l = this.length; i < l; i++){
						if (!fn.call(bind, this[i], i, this)) return false;
					}
					return true;
				},
				filter: function(fn, bind){
					var results = [];
					for (var i = 0, l = this.length; i < l; i++){
						if (fn.call(bind, this[i], i, this)) results.push(this[i]);
					}
					return results;
				},
				indexOf: function(item, from){
					var len = this.length;
					for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
						if (this[i] === item) return i;
					}
					return -1;
				},
				map: function(fn, bind){
					var results = [];
					for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this);
					return results;
				},
				some: function(fn, bind){
					for (var i = 0, l = this.length; i < l; i++){
						if (fn.call(bind, this[i], i, this)) return true;
					}
					return false;
				},
				contains: function(item, from){
					return this.indexOf(item, from) != -1;
				},
				//扩展，合并，拷贝;
				extend: function(array){
					for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
					return this;
				},
				getLast: function(){
					//return (this.length) ? this[this.length - 1] : null;
					return this.length>0?this[this.length-1]:void 0
				},
				//得到随机抽去的数组中的一个;
				getRandom: function(){
					return (this.length) ? this[M.$Random(0, this.length - 1)] : null;
				},
				//数组重新洗牌;
				random: function(){
					var nr=[], me=this, t;
					while(me.length>0){
						nr[nr.length] = me[t = Math.floor(Math.random() * me.length)];
						me = me.del(t);
					}
					return nr;
				},
				// 数字数组排序
				sortNum: function(f){
					if (!f) f=0;
					if (f==1) return this.sort(function(a,b){return b-a;});
					return this.sort(function(a,b){return a-b;});
				},
				//去掉重复
				removeRepeat:function(){
					this.sort();
					var rs = [];
					var cr = false;
					for (var i=0; i<this.length; i++){
						if (!cr) cr = this[i];
						else if (cr==this[i]) rs[rs.length] = i;
						else cr = this[i];
					}
					var re = this;
					for (var i=rs.length-1; i>=0; i--) re = re.del(rs[i]);
					return re;
				},
				include: function(item){
					if (!this.contains(item)) this.push(item);
					return this;
				},
				merge: function(array){
					for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
					return this;
				},
				//item 为数组的值;依值删除;
				remove: function(item){
					for (var i = this.length; i--; i){
						if (this[i] === item) this.splice(i, 1);
					}
					return this;
				},
				//依据索引删除
				del:function(index){
					if (index<0) return this;
					return this.slice(0,index).concat(this.slice(index+1,this.length));
				},
				clear: function(){
					this.length = 0;
					return this;
				}, 
				toJSON: function() {
					var results = [];
					this.each(function(object) {
					  var value = Object.toJSON(object);
					  if (value !== undefined) results.push(value);
					});
					return '[' + results.join(', ') + ']';
				  }

	})	 
	//Function 扩展；
	M.Extend(Function,{		
				extend: function(properties){
					for (var property in properties) this[property] = properties[property];
				} 			
					
	})
	/////////选择器扩展//////////
	M.getAllChildren=function(e) {
			return e.all ? e.all : e.getElementsByTagName('*');
	}
	
/////////选择器/////////
/*
实现对element的选取，支持css选取
M.Selecter("div#foo a.blog")
选取id为foo 的层中所有样式为blog的链接 
返回的是对像数组;
*/
	M.Selecter = function(selector) {
	selector = selector || document;
	 if( selector.nodeType ) {
			this[0] = selector;
			this.length = 1;
			return this;		 
	 }
	 
	  
	  if (!document.getElementsByTagName){return new Array();}			   
	  var tokens = selector.split(' ');
	  var currentContext = new Array(document);
	  for (var i = 0; i < tokens.length; i++) {
		token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
		if (token.indexOf('#') > -1) {					
			  var bits = token.split('#');
			  var tagName = bits[0];
			  var id = bits[1];
			 
			  var element = document.getElementById(id);
			  if (tagName && element.nodeName.toLowerCase() != tagName) {
					 return new Array();
			  }		
			 
			  currentContext = new Array(element);
			  
			  continue; 
		}
		


		if (token.indexOf('.') > -1) {					 
			  var bits = token.split('.');
			  var tagName = bits[0];
			  var className = bits[1];
			  if (!tagName) {
				tagName = '*';
			  }					 
			  var found = new Array;
			  var foundCount = 0;
			  for (var h = 0; h < currentContext.length; h++) {
					var elements;
					if (tagName == '*') {
						elements = M.getAllChildren(currentContext[h]);
					} else {
						elements = currentContext[h].getElementsByTagName(tagName);
					}
					for (var j = 0; j < elements.length; j++) {
					  found[foundCount++] = elements[j];
					}
			  }
			  currentContext = new Array;
			  var currentContextIndex = 0;
			  for (var k = 0; k < found.length; k++) {
					if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
					  currentContext[currentContextIndex++] = found[k];
					}
			  }
			  continue; 
		}
	
		
		if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
				  var tagName = RegExp.$1;
				  var attrName = RegExp.$2;
				  var attrOperator = RegExp.$3;
				  var attrValue = RegExp.$4;
				  if (!tagName) {
					tagName = '*';
				  }						 
				  var found = new Array;
				  var foundCount = 0;
				  for (var h = 0; h < currentContext.length; h++) {
						var elements;
						if (tagName == '*') {
							elements = getAllChildren(currentContext[h]);
						} else {
							elements = currentContext[h].getElementsByTagName(tagName);
						}
						for (var j = 0; j < elements.length; j++) {
						  found[foundCount++] = elements[j];
						}
				  }
				  currentContext = new Array;
				  var currentContextIndex = 0;
				  var checkFunction; // This function will be used to filter the elements
				  switch (attrOperator) {
					case '=': // Equality
					  checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
					  break;
					case '~': // Match one of space seperated words 
					  checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
					  break;
					case '|': // Match start with value followed by optional hyphen
					  checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
					  break;
					case '^': // Match starts with value
					  checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
					  break;
					case '$': // Match ends with value - fails with "Warning" in Opera 7
					  checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
					  break;
					case '*': // Match ends with value
					  checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
					  break;
					default :
					  // Just test for existence of attribute
					  checkFunction = function(e) { return e.getAttribute(attrName); };
					}
				  currentContext = new Array;
				  var currentContextIndex = 0;
				  for (var k = 0; k < found.length; k++) {
					if (checkFunction(found[k])) {
					  currentContext[currentContextIndex++] = found[k];
					}
				  }
				  // alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
				  continue; // Skip to next token
			 }
				// If we get here, token is JUST an element (not a class or ID selector)
				tagName = token;
				var found = new Array;
				var foundCount = 0;
				for (var h = 0; h < currentContext.length; h++) {
				  var elements = currentContext[h].getElementsByTagName(tagName);
				  for (var j = 0; j < elements.length; j++) {
					found[foundCount++] = elements[j];
				  }
				}
				currentContext = found;
			  }
			 
			 return currentContext;
	} 	
	M.$=function(){
		var elem = null;	
		if(typeof arguments[0] !="string"){
			if(!arguments[0]){return null;}
			elem = arguments[0];		 
			if(!elem.uid){				
				M.Element.apply(elem);				 
			}			 
			return elem;
		}	 
	    elem=M.Selecter(arguments[0]) 
		elem.each(function(i,n,b){
			try{
				if(!b[n].uid){
					M.Element.apply(b[n]);
				}else{
					//alert(b[n].uid)
				}
			}catch(e){
				//alert(e)
			}
		})	   
		this.size=function(){return elem.lenth}
		return elem.length==1?elem[0]:elem;
	}
	M.Cookies = {
		get : function(n){
			var dc = "; "+document.cookie+"; ";
			var coo = dc.indexOf("; "+n+"=");
			if (coo!=-1){
				var s = dc.substring(coo+n.length+3,dc.length);
				return unescape(s.substring(0, s.indexOf("; ")));
			}else{
				return null;
			}
		},
		set : function(name,value,expires,path,domain,secure){
			var expDays = expires*24*60*60*1000;
			var expDate = new Date();
			expDate.setTime(expDate.getTime()+expDays);
			var expString = expires ? "; expires="+expDate.toGMTString() : "";
			var pathString = "; path="+(path||"/");
			var domain = domain ? "; domain="+domain : "";
			document.cookie = name + "=" + escape(value) + expString + domain + pathString + (secure?"; secure":"");
		},

		del : function(n){
			var exp = new Date();
			exp.setTime(exp.getTime() - 1);
			var cval=this.get(n);
			if(cval!=null) document.cookie= n + "="+cval+";expires="+exp.toGMTString();
		}
    };
	///跳转页面;
	 M.Redirect = function(url,paraStr){
		if(!paraStr){
			location.href=url;
			return;
		}
		var obj = {};
		if(url.indexOf("?")!=-1){
			var s = url.substring(url.indexOf("?")+1).split("&");
			for(var i=0; i<s.length; i++){
				var j=s[i].split("=");
				obj[j[0].toString().toLowerCase()]=j[1]||"";
			}		
		}
		var t = paraStr.split("&");
		for(var i=0; i<t.length; i++){
			var j = t[i].split("=");
			obj[j[0].toString().toLowerCase()]=j[1]||"";
		}
		location.href=url.substring(0,url.indexOf("?"))+"?"+$.Form.serialize(obj);
	};
	///	
	
 })();
//检测数据类型;
function $type(obj){
	if (obj == undefined) return false;
 	if (obj.nodeName){
		switch (obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}	 
	switch(typeof(obj)+""){	
		case "object" :		     
			  return obj.constructor==Array?'array':
			  obj.constructor==Object?'object':'undefined';
			  break;
		case "function" :
			 return obj.constructor==Function?"fucntion":'';
			 break;
		default:
			 return typeof obj;
			 break;
	}	
};
function $exec(text){
	if(IsEmpty(text)) return false;
	if (window.execScript){
		
		window.execScript(text);
	} else {
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		script.text = text;
		document.getElementsByTagName('head')[0].appendChild (script)		
		document.getElementsByTagName('head')[0].removeChild(script);
	}
	return text;
};
//空对像;
$empty=function(){}
function empty(){}
/*
 arguments.callee.$.getName.call(this);
*/
function Class() {}
(function(c){
	c.prototype.constrcut=c;
	c.Extend=function(o) {	  
		var p =function() {			 
			 if (arguments[0]!== c) {this.construct.apply(this, arguments);}
		};
		var t =new this(c);
		var s =this.prototype;
		for (var n in o) {
			var i = o[n];
			if (i instanceof Function) i.$ = s;
			t[n]= i;
		}
		p.prototype = t;
		p.ok='function'
		p.Extend =this.Extend;
		return p;
	}
})(Class);
 

 
//正则扩展;
/*
var b=["a","3ab","abca"].filter(/^a/) 
alert(b)

*/
RegExp.prototype.call = function (context, str) {
	return this.exec(str);
};
RegExp.prototype.apply = function (context, args) {
	return this.exec(args[0]);
}; 
Function.prototype.addMethod=function(a,b){			 
	if(!this.prototype[a])this.prototype[a]=b;
	return this;
}
Function.addMethod("as",function(e,f){
	var b=e?e.split("."):[];
	if(b.length>0){
		var a=window;
		for(var d=0;d<b.length-1;++d){
			var c=b[d];
			if(c){
				if(!a[c])a[c]={} ;
				a=a[c]
			} 
		}
		a[b.getLast()]=f?new this:this
	} 
	return this
})
//名称空间;
Function.addMethod("ns",function(a){
	this.as(a,1)
});
//延时执行函数;
Function.prototype.defer = function(s, a){ 
		var $= this;
		if(!(a instanceof Array))
			a = [a];
		 window.setTimeout(function(){
			return $.apply(this, a);
		}, s);	 
}
Function.prototype.listen = function(provider, delay, args)
{
	var $pointer = this;
	if(!(args instanceof Array))
		args = [args];
		setTimeout(function(){
		if(provider.apply($pointer, args)){
			$pointer.apply(null, args);
			$pointer.listen(provider, delay, args);
		}
	},delay);
}
 //js文件数组;
Mandala.jsFile=[];
Mandala.Import=function(url,callback){	
	 try{	 
	 callback=callback||function(){};	
	// alert(Mandala.$Jpath)
	 if(url.split("$M.")[1]==undefined){
		// throw '找不到对应的包文件';	
	 }else{
		 url=Mandala.$Jpath+url.split("$M.")[1].replace(".","/")+".js"
	  };
	 // alert(url)
	  //如果已经加载,则直接执行回调函数;
	 if(Mandala.jsFile.join(";").indexOf(url)!=-1){
		 
		return  callback()
	 };	 
	 var script = document.createElement('script'); 
	 script.type = 'text/javascript';  	
	 script.onload = script.onreadystatechange = function() {		  
		   if (script.readyState && script.readyState != 'loaded' && script.readyState != 'complete') {
		    return; 
		  }
		  script.onreadystatechange = script.onload = null; 
		  callback(); 
	}; 	
	 
	script.src = url; 	
	document.getElementsByTagName('head')[0].appendChild (script);
	Mandala.jsFile.push(url) ;
	}catch(e){
		alert(e)
	}
 }
 //批量导入文件;
Mandala.Include=function(a,callback){
  var j=0;x=a.length;
  a.each(function(i){
	Mandala.Import("$M."+i,function(){j++});
  })
   var a=window.setInterval(function(){             
		    if(j===x){
				callback();window.clearInterval(a)
				}else{
				}           
	}, 99);
}

 Mandala.Ready = (function(){
    // create event function stack
    var load_events = [],
        load_timer,
        script,
        done,
        exec,
        old_onload,
        init = function () {
            done = true;

            // kill the timer
            clearInterval(load_timer);

            // execute each function in the stack in the order they were added
            while (exec = load_events.shift())
                exec();         
			
			if (script) script.onreadystatechange = '';
			//自已加的
            try{
			document.execCommand("BackgroundImageCache",false,true)
			}catch(e){}
            ///
        };

    return function (func) {
        // if the init function was already ran, just run this function now and stop
        if (done) return func();

        if (!load_events[0]) {
            // for Mozilla/Opera9
            if (document.addEventListener)
                document.addEventListener("DOMContentLoaded", init, false);

            // for Internet Explorer
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
                script = document.getElementById("__ie_onload");
                script.onreadystatechange = function() {
                    if (this.readyState == "complete")
                        init(); // call the onload handler
                };
            /*@end @*/

            // for Safari
            if (/WebKit/i.test(navigator.userAgent)) { // sniff
                load_timer = setInterval(function() {
                    if (/loaded|complete/.test(document.readyState))
                        init(); // call the onload handler
                }, 10);
            }

            // for other browsers set the window.onload, but also execute the old window.onload
            old_onload = window.onload;
            window.onload = function() {
                init();
                if (old_onload) old_onload();
            };
        }

        load_events.push(func);
    }
//垃圾回收;
 

})();
var $M=window.Mandala;
}
